import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PrintFilterlog {

    public final static String DEFAULT_PATTERN_DATETIME_SIMPLE = "yyyyMMddHHmmss";
    public final static String DEFAULT_PATTERN_DATETIME_FULL = "yyyy-MM-dd HH:mm:ss.SSS";
    public final static String pattern = ".*(\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}.\\d{3}).*";

    public static void main(String[] args) throws Exception {
        if(args == null || args.length == 0) {
            System.out.println("传入参数为空");
        }
        if(args.length !=3) {
            System.out.println("传入参数不正确， 应该传入: 文件名 开始时间【yyyymmddhhmiss】 结束时间【yyyymmddhhmiss】");
        }
        String fileName = args[0];
        String startDateStr = args[1];
        String endDateStr = args[2];

        Date startDate = new SimpleDateFormat(DEFAULT_PATTERN_DATETIME_SIMPLE).parse(startDateStr);
        Date endDate = new SimpleDateFormat(DEFAULT_PATTERN_DATETIME_SIMPLE).parse(endDateStr);

        File file = new File(fileName);
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String tempString = null;

        boolean isPreMatch = false;
        while ((tempString = reader.readLine()) != null) {
            boolean thisMatch = false;
            Pattern  r = Pattern.compile(pattern);
            Matcher m = r.matcher(tempString);
            if(m.find()) {
                Date logDate = new SimpleDateFormat(DEFAULT_PATTERN_DATETIME_FULL).parse(m.group(1));
                if(logDate.after(startDate) && logDate.before(endDate)) {
                    isPreMatch = true;
                    thisMatch = true;
                }
                if(logDate.after(endDate) || logDate.before(startDate)) {
                    isPreMatch = false;
                }

                if(logDate.after(endDate)){
                    System.exit(0);
                }
            }

            if(isPreMatch||thisMatch) {
                System.out.println(tempString);
            }
        }
        reader.close();
    }
}
